@using OrchardCore.DisplayManagement
@using OrchardCore.DisplayManagement.Implementation
@{
    if (Model is not IShape shape || shape.As<BootstrapSplitButton>() is not { } viewModel) { return; }

    const string bootstrapSplitButton = "bootstrapSplitButton";

    var type = string.IsNullOrWhiteSpace(viewModel.Type) ? "primary" : viewModel.Type;
    var classes = $"btn btn-{type}";
    var options = viewModel.Options.AsList();
    var disabled = !options.Any();
    var shadowOffset = type == "primary" ? 0 : 8;
}

<div class="btn-group @bootstrapSplitButton @viewModel.WrapperClasses">
    <button type="button"
            class="@(bootstrapSplitButton)__main @classes @viewModel.ButtonClasses"
            disabled="@disabled">
        @(string.IsNullOrWhiteSpace(viewModel.Text) ? options.FirstOrDefault().Text : viewModel.Text)
    </button>
    <button type="button"
            class="dropdown-toggle dropdown-toggle-split @(bootstrapSplitButton)__dropdownButton @classes @viewModel.ToggleClasses"
            disabled="@disabled"
            aria-expanded="false">
        <span class="visually-hidden">@T["Toggle Dropdown"]</span>
    </button>
    <div class="w-100 h-100 fixed-bottom @(bootstrapSplitButton)__screen"></div>
    <ul class="@(bootstrapSplitButton)__dropdownMenu dropdown-menu @viewModel.DropdownClasses">
        @foreach (var option in options)
        {
            <li class="@(bootstrapSplitButton)__dropdownMenuItem">
                @if (option.Text?.Trim().StartsWith("---") == true)
                {
                    <hr class="dropdown-divider">
                }
                else
                {
                    <a href="@option.Url" class="dropdown-item">@option.Text</a>
                }
            </li>
        }
    </ul>
</div>

<script asp-name="BootstrapSplitButtonScript" at="Foot">
Array.from(document.querySelectorAll('.bootstrapSplitButton'))
    .forEach((block) => {
        const toggler = block.querySelector('.bootstrapSplitButton__dropdownButton');
        const menu = block.querySelector('.bootstrapSplitButton__dropdownMenu');

        const screen = block.querySelector('.bootstrapSplitButton__screen');
        screen.style.zIndex = 'auto';
        screen.hidden = true;
        screen.addEventListener('click', () => toggler.click());

        block.querySelector('.bootstrapSplitButton__main')
            .addEventListener('click', () => block.querySelector('a.dropdown-item').click());

        toggler
            .addEventListener('click', (event) => {
                const expanded = event.target.getAttribute('aria-expanded') === 'false';
                event.target.setAttribute('aria-expanded', expanded);
                screen.hidden = !expanded;
                menu.classList[expanded ? 'add' : 'remove']('show');
                menu.style.marginTop = (toggler.offsetHeight + @shadowOffset) + 'px';
            });
    });
</script>
